/**
 * Carnegie Mellon University
 * School of Computer Science
 * MSIT eBusiness Technology
 * 
 * Team 8 - Infinity (2011 Spring)
 * infinity-team8@googlegroups.com
 * 
 * Professor: Jeffrey L. Eppinger
 * Program Faculty: Sujata Telang
 */

package controller;


import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.FundDAO;
import model.Model;
import model.CustomerDAO;
import model.TransactionDAO;

import org.mybeans.dao.DAOException;
import org.mybeans.form.FormBeanException;
import org.mybeans.form.FormBeanFactory;

import databean.CustomerBean;
import databean.TransactionBean;
import formbean.CustomerBuyFundForm;

public class CustomerBuyFundAction extends Action {
	private FormBeanFactory<CustomerBuyFundForm> formBeanFactory = FormBeanFactory.getInstance(CustomerBuyFundForm.class);
	
	private CustomerDAO customerDAO;
	private FundDAO  fundDAO;
	private TransactionDAO transactionDAO;

	public CustomerBuyFundAction(Model model) {
		customerDAO = model.getCustomerDAO();
		fundDAO = model.getFundDAO();
		transactionDAO = model.getTransactionDAO();
	}

	public String getName() { return "customer-buy-fund.do"; }
    
    public String perform(HttpServletRequest request,HttpServletResponse response) {
    	// Set up error list
        List<String> errors = new ArrayList<String>();
        request.setAttribute("errors",errors);

        try {
        	// Load the form parameters into a form bean
			CustomerBuyFundForm form = formBeanFactory.create(request);
			request.setAttribute("form",form);
			
            // Set up user list for nav bar
			request.setAttribute("fundList",fundDAO.getFunds());
			
			request.getSession().setAttribute("customer",(CustomerBean) request.getSession(false).getAttribute("customer"));
	        request.setAttribute("customerList",customerDAO.getCustomers());
	                
	        // If no params were passed, return with no errors so that the form will be
	        // presented (we assume for the first time).
	        if (!form.isPresent()) {
	            return "customer-buy-fund.jsp";
	        }
	
	        // Check for any validation errors
	        errors.addAll(form.getValidationErrors());
	        if (errors.size() != 0) {
	            return "customer-buy-fund.jsp";
	        }
	
			CustomerBean customer = (CustomerBean) request.getSession().getAttribute("customer");
	
			
			//get available cash minus the amount customer entered this time
			//if result goes negative, return failure
			if ((customerDAO.getAvailableCash(customer.getUserName()) -
					(long) Math.round(Double.parseDouble(form.getAmount())*100)) < 0) {
				errors.add("You don't have sufficient cash balance in your account to support this transaction.");
		        return "customer-buy-fund.jsp";
			}

			// Create "Buy Fund" transaction			
			TransactionBean transaction = new TransactionBean(0);
			transaction.setCustomerID(customer.getCustomerID());
			transaction.setTransactionType("buy");
			transaction.setFundID(Long.parseLong(form.getFundID()));
			transaction.setAmount((long) Math.round(Double.parseDouble(form.getAmount())*100));
			
			transactionDAO.create(transaction);
	
			request.setAttribute("message","Fund has been scheduled for buying for "+customer.getUserName()+" on the next transition day.");
	        return "customer-success.jsp";
        } catch (DAOException e) {
        	errors.add(e.toString());
        	return "customer-buy-fund.jsp";
        } catch (FormBeanException e) {
        	errors.add(e.toString());
        	return "customer-buy-fund.jsp";
        } catch (NumberFormatException e) {
        	errors.add("Input must be numeric.");
        	return "customer-buy-fund.jsp";
        }
    }
}
